package com.example.pcbcsmbackend.service;

import com.example.pcbcsmbackend.entity.Product;
import com.example.pcbcsmbackend.repository.ProductRepository;
import com.example.pcbcsmbackend.repository.OrderDetailRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class ProductService {
    
    @Autowired
    private ProductRepository productRepository;
    
    @Autowired
    private OrderDetailRepository orderDetailRepository;
    
    // 添加商品
    public Product addProduct(String productName, String specParams, BigDecimal price, 
                             Integer stock, String productImage, Integer categoryId, String description) {
        Product product = new Product(productName, specParams, price, stock, productImage, categoryId, description);
        return productRepository.save(product);
    }
    
    // 根据ID查找商品
    public Optional<Product> findById(Integer productId) {
        return productRepository.findById(productId);
    }
    
    // 获取所有商品
    public List<Product> getAllProducts() {
        return productRepository.findAll();
    }
    
    // 分页获取商品
    public Page<Product> getProductsByPage(int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        return productRepository.findAll(pageable);
    }
    
    // 根据分类获取商品
    public List<Product> getProductsByCategory(Integer categoryId) {
        return productRepository.findByCategoryId(categoryId);
    }
    
    // 搜索商品
    public List<Product> searchProducts(String keyword) {
        return productRepository.findByProductNameContaining(keyword);
    }
    
    // 获取热门商品（前10个）
    public List<Product> getHotProducts() {
        Pageable pageable = PageRequest.of(0, 10);
        return productRepository.findTopProducts();
    }
    
    // 根据价格范围查找商品
    public List<Product> getProductsByPriceRange(BigDecimal minPrice, BigDecimal maxPrice) {
        return productRepository.findByPriceBetween(minPrice, maxPrice);
    }
    
    // 更新商品
    public Product updateProduct(Product product) {
        product.setUpdatedAt(LocalDateTime.now());
        return productRepository.save(product);
    }
    
    // 删除商品
    @Transactional
    public void deleteProduct(Integer productId) {
        try {
            // 先删除包含该商品的订单详情
            orderDetailRepository.deleteByProductId(productId);
            
            // 删除商品
            productRepository.deleteById(productId);
        } catch (Exception e) {
            throw new RuntimeException("删除商品失败: " + e.getMessage());
        }
    }
    
    // 批量删除商品
    @Transactional
    public void batchDeleteProducts(List<Integer> productIds) {
        try {
            // 先删除包含这些商品的订单详情
            orderDetailRepository.deleteByProductIdIn(productIds);
            
            // 批量删除商品
            productRepository.deleteAllById(productIds);
        } catch (Exception e) {
            throw new RuntimeException("批量删除商品失败: " + e.getMessage());
        }
    }
    
    // 减少库存
    public void decreaseStock(Integer productId, Integer quantity) {
        Optional<Product> productOpt = productRepository.findById(productId);
        if (productOpt.isPresent()) {
            Product product = productOpt.get();
            if (product.getStock() >= quantity) {
                product.setStock(product.getStock() - quantity);
                productRepository.save(product);
            } else {
                throw new RuntimeException("库存不足");
            }
        } else {
            throw new RuntimeException("商品不存在");
        }
    }
} 